<script setup lang="ts">
import { ref, watch } from 'vue'
import { api as viewerApi } from 'v-viewer'
import 'viewerjs/dist/viewer.css'

interface Props {
  imgUrl?: string
  disabled?: boolean
  size?: string
}

const { imgUrl, disabled = false, size = '96px' } = defineProps<Props>()

const emit = defineEmits<{
  (e: 'image-remove', val: any): void
}>()

const imageRemove = () => {
  emit('image-remove', imgUrl)
}

const imagePreview = () => {
  if (imgUrl) {
    viewerApi({
      images: [imgUrl],
      options: {
        zIndex: 9999
      }
    })
  }
}

const bindSize = ref(size)

watch(
  () => size,
  (newVal) => {
    if (newVal.includes('px')) {
      bindSize.value = newVal
    } else {
      if (!isNaN(Number(newVal))) {
        bindSize.value = `${newVal}px`
      } else {
        bindSize.value = '96px'
      }
    }
  },
  {
    immediate: true
  }
)
</script>

<template>
  <ul class="el-upload-list el-upload-list--picture-card">
    <li class="el-upload-list__item is-ready" tabindex="0">
      <img class="el-upload-list__item-thumbnail" :src="imgUrl" alt="" />
      <span class="el-upload-list__item-actions">
        <span class="el-upload-list__item-preview" @click="imagePreview">
          <i class="el-icon el-icon--zoom-in">
            <svg class="icon" width="200" height="200" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
              <path
                fill="currentColor"
                d="M795.904 750.72l124.992 124.928a32 32 0 01-45.248 45.248L750.656 795.904a416 416 0 1145.248-45.248zM480 832a352 352 0 100-704 352 352 0 000 704zm-32-384v-96a32 32 0 0164 0v96h96a32 32 0 010 64h-96v96a32 32 0 01-64 0v-96h-96a32 32 0 010-64h96z"
              ></path>
            </svg>
          </i>
        </span>
        <span v-if="!disabled" class="el-upload-list__item-delete" @click="imageRemove">
          <i class="el-icon el-icon--delete">
            <svg class="icon" width="200" height="200" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
              <path
                fill="currentColor"
                d="M160 256H96a32 32 0 010-64h256V95.936a32 32 0 0132-32h256a32 32 0 0132 32V192h256a32 32 0 110 64h-64v672a32 32 0 01-32 32H192a32 32 0 01-32-32V256zm448-64v-64H416v64h192zM224 896h576V256H224v640zm192-128a32 32 0 01-32-32V416a32 32 0 0164 0v320a32 32 0 01-32 32zm192 0a32 32 0 01-32-32V416a32 32 0 0164 0v320a32 32 0 01-32 32z"
              ></path>
            </svg>
          </i>
        </span>
      </span>
    </li>
  </ul>
</template>

<style lang="scss" scoped>
.el-upload-list__item.is-ready {
  @include rect(v-bind(bindSize), v-bind(bindSize));
}
</style>
